<template>
	<view class="min-h-screen bg-[var(--page-bg-color)] overflow-hidden">
		<view class="mescroll-box bg-[var(--page-bg-color)]"
			:class="{ 'cart': config.cart.control && config.cart.event === 'cart', 'detail': !(config.cart.control && config.cart.event === 'cart') }"
			v-if="tabsData.length">
			<mescroll-body ref="mescrollRef" :down="{ use: false }" @init="mescrollInit" @up="getListFn">
				<view v-if="config.search.control"
					class="search-box z-10 bg-[#fff] fixed top-0 left-0 right-0 h-[100rpx] box-border">
					<view class="flex-1 search-input">
						<text @click.stop="searchNameFn" class="nc-iconfont nc-icon-sousuo-duanV6xx1 btn"></text>
						<input class="input" type="text" v-model="searchName" :placeholder="config.search.title"
							@confirm="searchNameFn" placeholderClass="text-[var(--text-color-light9)]">
						<text v-if="searchName" class="nc-iconfont nc-icon-cuohaoV6xx1 clear" @click="searchName = ''"></text>
					</view>
				</view>
				<!--  #ifdef  H5 || APP-PLUS -->
				<view class="tabs-box z-2 fixed left-0 bg-[#fff] bottom-[50px] top-0"
					:class="{ '!top-[100rpx]': config.search.control, 'pb-[98rpx]': config.cart.control && config.cart.event === 'cart' }">
					<scroll-view :scroll-y="true" class="scroll-height">
						<view class="bg-[var(--temp-bg)]">
							<view class="tab-item"
								:class="{ 'tab-item-active': index == tabActive, 'rounded-br-[12rpx]': tabActive - 1 === index, 'rounded-tr-[12rpx]': tabActive + 1 === index }"
								v-for="(item, index) in tabsData" :key="index" @click="firstLevelClick(index, item)">
								<view class="text-box text-left leading-[1.3] break-words px-[16rpx]">
									{{ item.category_name }}
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<!--  #endif -->
				<!--  #ifdef  MP-WEIXIN -->
				<view class="tabs-box z-2 fixed left-0 bg-[#fff] pb-ios bottom-[100rpx] top-0"
					:class="{ 'top-[126rpx]': config.search.control, '!bottom-[148rpx]': config.cart.control && config.cart.event === 'cart' }">
					<scroll-view :scroll-y="true" class="scroll-height">
						<view class="bg-[var(--temp-bg)]">
							<view class="tab-item"
								:class="{ 'tab-item-active': index == tabActive, 'rounded-br-[12rpx]': tabActive - 1 === index, 'rounded-tr-[12rpx]': tabActive + 1 === index }"
								v-for="(item, index) in tabsData" :key="index" @click="firstLevelClick(index, item)">
								<view class="text-box text-left leading-[1.3] break-words px-[16rpx]">
									{{ item.category_name }}
								</view>
							</view>
						</view>
					</scroll-view>
				</view>
				<!--  #endif -->
				<view class="flex justify-center flex-wrap pl-[188rpx] pb-[20rpx]"
					:class="{ ' pt-[120rpx]': config.search.control, ' pt-[20rpx]': !(config.search.control) }">
					<template v-for="(item, index) in list" :key="item.orderId">
						<view
							class="box-border bg-white w-full flex mr-[20rpx] py-[24rpx] px-[20rpx] rounded-[var(--rounded-small)] relative"
							:class="{ 'mt-[16rpx]': index }">
							<view
								class="w-[168rpx] h-[168rpx] flex items-center justify-center rounded-[var(--goods-rounded-small)] overflow-hidden">
								<u--image width="168rpx" height="168rpx" radius="var(--goods-rounded-small)"
									:src="img(item.picUrl || '')" model="aspectFill">
									<template #error>
										<image class="w-[168rpx] h-[168rpx]" :src="img('static/resource/images/diy/shop_default.jpg')"
											mode="aspectFill"></image>
									</template>
								</u--image>

							</view>
							<view class="flex flex-1 ml-[20rpx] flex-wrap flex-col">
								<view class="max-h-[80rpx] text-[32rpx] leading-[40rpx] font-bold multi-hidden">
									{{ item.spuName }}
								</view>
								<view class="flex-1 flex items-end justify-between">
									<view class=" -mb-[8rpx]" style="word-break: keep-all">
										<text class="text-[24rpx] ">提货订单:{{ item.no }}</text>
									</view>
								</view>
								<!-- <view class="flex-1 flex items-end justify-between">
									<view class=" price-font -mb-[8rpx]">
										<text class="text-[24rpx] "> 购买时间:{{ timeFormat(item.tradeTime,
											'yyyy-mm-dd') }}</text>
									</view>
								</view> -->
								<!-- <view class="flex-1 flex items-end justify-between">
									<view class=" price-font -mb-[8rpx]">
										<text class="text-[24rpx] ">购买数量:{{ item.count }}</text>
									</view>
								</view> -->
								<view class="flex-1 flex items-end justify-between" v-if="item.leavePrice > 0">
									<view class=" price-font -mb-[8rpx]">
										<text class="text-[24rpx] ">剩余欠款:￥{{ fen2yuan(item.leavePrice) }}</text>
									</view>
								</view>
								<view class="flex-1 flex items-end justify-between">
									<view class="text-[var(--price-text-color)] price-font -mb-[8rpx]">
										<text class="text-[28rpx] font-500">可提货数量:{{ item.leaveNumber
										}}</text>
									</view>

									<template v-if="item.orderId">
										<view v-if="config.cart.control && config.cart.style === 'style-1'" class="h-[44rpx] relative">
											<view :id="'itemCart' + index"
												class="w-[102rpx] box-border text-center text-[#fff] primary-btn-bg h-[46rpx] text-[28rpx] leading-[46rpx] rounded-[100rpx]"
												@click.stop="itemCart(item, 'itemCart' + index)">
												{{ config.cart.text }}
											</view>

										</view>



									</template>
								</view>
							</view>
						</view>

					</template>
					<mescroll-empty class="part" v-if="!list.length && !loading && listLoading"
						:option="{ tip: '暂无商品' }"></mescroll-empty>
				</view>
				<add-cart-popup ref="cartRef" />
			</mescroll-body>

			<!--  #ifdef  H5 || APP-PLUS -->
			<view v-if="config.cart.control && config.cart.event === 'cart'"
				class="bg-[#fff] z-10 flex justify-between items-center fixed left-0 right-0 bottom-[0px] box-solid px-[24rpx]  pb-ios border-[0] border-t-[2rpx] border-solid border-[#f6f6f6]">
				<view class="flex items-center py-[17rpx]">
					<view class="w-[84rpx] h-[84rpx] mr-[27rpx] relative">
						<view id="animation-end"
							class="w-[84rpx] h-[84rpx] rounded-[50%] bg-[var(--primary-color)] text-center leading-[84rpx]"
							@click.stop="toCart">
							<text class="nc-iconfont nc-icon-gouwucheV6mm1 text-[#fff] text-[36rpx]"></text>
						</view>
						<view v-if="totalNum" class="border-[1rpx] border-solid border-[#fff]"
							:class="['absolute left-[40rpx] top-[-10rpx] rounded-[36rpx] h-[36rpx] min-w-[36rpx] text-center leading-[36rpx] bg-[#FF4646] text-[#fff] text-[20rpx] font-500 box-border', totalNum > 9 ? 'px-[10rpx]' : '']">
							{{ totalNum > 99 ? "99+" : totalNum }}
						</view>
					</view>
					<!-- <text class="text-[26rpx] font-500 text-[#333]">总计：</text> -->
					<view class="text-[var(--price-text-color)] price-font font-bold flex items-baseline">
						<!-- <text class="text-[26rpx] mr-[6rpx]">￥</text> -->
						<!-- <text class="text-[44rpx]">{{ parseFloat(diyGoods.fen2yuan(totalMoney)) }}</text> -->
					</view>
				</view>
				<button class="w-[240rpx] h-[84rpx] text-[36rpx] leading-[84rpx] font-500 m-0 rounded-[42rpx] remove-border"
					:class="{ 'primary-btn-bg !text-[#fff]': parseFloat(totalNum) > 0, 'bg-[#F7F7F7] !text-[var(--text-color-light9)]': parseFloat(totalNum) <= 0 }"
					@click="toCart">提货</button>
			</view>
			<!--  #endif -->

			<!-- #ifdef MP-WEIXIN -->
			<view v-if="config.cart.control && config.cart.event === 'cart'"
				class="bg-[#fff] z-10 flex justify-between items-center fixed left-0 right-0 bottom-0 box-solid px-[24rpx]  pb-ios border-[0] border-t-[2rpx] border-solid border-[#f6f6f6]">
				<view class="flex items-center py-[17rpx]">
					<view class="w-[84rpx] h-[84rpx] mr-[27rpx] relative">
						<view id="animation-end"
							class="w-[84rpx] h-[84rpx] rounded-[50%] bg-[var(--primary-color)] text-center leading-[84rpx]"
							@click.stop="toCart">
							<text class="nc-iconfont nc-icon-gouwucheV6mm1 text-[#fff] text-[36rpx]"></text>
						</view>
						<view v-if="totalNum" class="border-[1rpx] border-solid border-[#fff]"
							:class="['absolute left-[40rpx] top-[-10rpx] rounded-[36rpx] h-[36rpx] min-w-[36rpx] text-center leading-[36rpx] bg-[#FF4646] text-[#fff] text-[20rpx] font-500 box-border', totalNum > 9 ? 'px-[10rpx]' : '']">
							{{ totalNum > 99 ? "99+" : totalNum }}
						</view>
					</view>
					<!-- <text class="text-[26rpx] font-500 text-[#333]">总计：</text>
					<view class="text-[var(--price-text-color)] price-font font-bold inline-block">
						<text class="text-[26rpx] mr-[6rpx]">￥</text>
						<text class="text-[44rpx]">{{ parseFloat(diyGoods.fen2yuan(totalMoney)) }}</text>
					</view> -->
				</view>
				<!-- <button v-if="isBindMobile && userInfo && !userInfo.mobile"
					class="w-[240rpx] h-[84rpx] text-[36rpx] leading-[84rpx] font-500 m-0 rounded-full remove-border"
					:class="{ 'primary-btn-bg !text-[#fff]': parseFloat(totalMoney) > 0, 'bg-[#F7F7F7] !text-[var(--text-color-light9)]': parseFloat(totalMoney) <= 0 }"
					open-type="getPhoneNumber" @getphonenumber="memberStore.bindMobile">去结算</button> -->
				<button class="w-[240rpx] h-[84rpx] text-[36rpx] leading-[84rpx] font-500 m-0 rounded-full remove-border"
					:class="{ 'primary-btn-bg !text-[#fff]': parseFloat(totalNum) > 0, 'bg-[#F7F7F7] !text-[var(--text-color-light9)]': parseFloat(totalNum) <= 0 }"
					@click="toCart">提货</button>
			</view>
			<!--  #endif -->
		</view>

		<view v-show="animationElStatus" :style="animationElStatus"
			class="fixed z-999 flex items-center justify-center text-[#fff] bg-color h-[44rpx] w-[44rpx] rounded-[22rpx] text-center">
			<text class=" nc-iconfont nc-icon-gouwucheV6xx6 !text-[30rpx]"></text>
		</view>
		<mescroll-empty v-if="!tabsData.length && !loading" :option="{ tip: '暂无商品分类' }"></mescroll-empty>
		<loading-page :loading="loading"></loading-page>

		<!-- 强制绑定手机号 -->
		<bind-mobile ref="bindMobileRef" />

	</view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, getCurrentInstance, reactive } from 'vue';
import { t } from '@/locale';
import { img, redirect, getToken } from '@/utils/common';
import { getGoodsPages } from '@/addon/pickUp/api/goods';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import bindMobile from '@/components/bind-mobile/bind-mobile.vue';
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import useMemberStore from '@/stores/member'
import useCartStore from '@/addon/pickUp/stores/cart'
import { fen2yuan, timeFormat } from '@/utils/formatting';




const cartStore = useCartStore();

// 查询购物车列表
cartStore.getList();

const cartList = computed(() => cartStore.cartList)
console.log(cartList.value)
const totalNum = computed(() => cartStore.totalNum)
// const totalMoney = computed(() => cartStore.totalMoney)
const memberStore = useMemberStore()
const userInfo = computed(() => memberStore.info)
const { mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const prop = defineProps({
	config: {
		type: Object,
		default: (() => { return {} })
	},
	categoryId: {
		type: [String, Number],
		default: 0
	}
})
let config = prop.config
let categoryId = prop.categoryId;
const list = ref<Array<Object>>([]);
const searchName = ref("");
const loading = ref<boolean>(true);//页面加载动画
const listLoading = ref<boolean>(false);//列表加载动画
const cartData = ref<Array<any>>([])
const instance = getCurrentInstance(); // 获取组件实例
cartData.value = uni.getStorageSync('shopCart') || []
interface acceptingDataStructure {
	data: acceptingDataItemStructure,
	msg: string,
	code: number
}
interface acceptingDataItemStructure {
	data: object,
	[propName: string]: number | string | object
}
interface mescrollStructure {
	num: number,
	size: number,
	endSuccess: Function,
	[propName: string]: any
}
const getListFn = (mescroll: mescrollStructure) => {
	listLoading.value = false
	getGoodsPages({
		pageNo: mescroll.num,
		pageSize: mescroll.size,
		spuName: searchName.value,
		reserveType: 1,


	}).then((res: any) => {
		let newArr = res.data.list
		//设置列表数据

		if (mescroll.num == 1) {
			list.value = []; //如果是第一页需手动制空列表
		}
		list.value = list.value.concat(newArr);
		loading.value = false;
		mescroll.endSuccess(newArr.length);
		if (!list.value.length) listLoading.value = true
	}).catch(() => {
		loading.value = false;
		listLoading.value = true
		mescroll.endErr(); // 请求失败, 结束加载
	})
}













onMounted(() => {
	getCategoryData()
})

//设置购物车动画
const animationElStatus = ref('')
const animationAddRepeatFlag = ref<Boolean>(false)
const cartRepeatFlag = ref<Boolean>(false)
const animationAddCart = (row: any, id: any) => {
	if (animationAddRepeatFlag.value || cartRepeatFlag.value) return false
	animationAddRepeatFlag.value = true
	cartRepeatFlag.value = true

	let obj: any = {
		orderItemId: row.orderItemId,
		skuId: row.skuId,
		count: 1,
		useCase: 8

	};
	console.log(obj)

	// 起购
	let num = 1;


	cartStore.increase(obj, num, () => {
		cartRepeatFlag.value = false
	});
	// #ifdef  MP-WEIXIN
	setTimeout(() => {
		uni.createSelectorQuery().in(instance).select('#animation-end').boundingClientRect((res: any) => {
			uni.createSelectorQuery().in(instance).select('#' + id).boundingClientRect((position: any) => {
				animationElStatus.value = `top: ${position.top}px; left: ${position.left}px;`
				setTimeout(() => {
					animationElStatus.value = `top: ${res.top + res.height / 2 - position.height / 3}px; left: ${res.left + res.width / 2 - position.width / 3}px; transition: all 0.8s; transform: rotate(-720deg);`
				}, 20);

				setTimeout(() => {
					animationElStatus.value = ''
					animationAddRepeatFlag.value = false
				}, 1020);

			}).exec()

		}).exec()
	}, 100)
	// #endif
	// #ifdef  H5
	setTimeout(() => {
		const animationEnd: any = window.document.getElementById('animation-end');
		const animationEndLeft = animationEnd.getBoundingClientRect().left;
		const animationEndTop = animationEnd.getBoundingClientRect().top;

		const itemCart: any = window.document.getElementById(id);
		const itemCartLift = itemCart.getBoundingClientRect().left;
		const itemCartTop = itemCart.getBoundingClientRect().top;
		animationElStatus.value = `top: ${itemCartTop}px; left: ${itemCartLift}px;`

		setTimeout(() => {
			animationElStatus.value = `top: ${animationEndTop + animationEnd.offsetHeight / 2 - itemCart.offsetHeight / 3}px; left: ${animationEndLeft + animationEnd.offsetWidth / 2 - itemCart.offsetHeight / 3}px; transition: all 0.8s; transform: rotate(-720deg);`
		}, 20);
		setTimeout(() => {
			animationElStatus.value = ''
			animationAddRepeatFlag.value = false
		}, 1020);

	}, 100);
	// #endif
}

/**
 * @description 获取分类数据
 * */
const tabsData: any = ref<Array<Object>>([])
const getCategoryData = () => {
	loading.value = true;
	tabsData.value = [
		{
			"pid": 0,
			"category_id": 0,
			"category_name": "全部",
			"category_full_name": "全部",
		},


	]
	if (categoryId) {
		for (let i = 0; i < tabsData.value.length; i++) {
			if (tabsData.value[i].category_id == categoryId) {
				tabActive.value = i;
				break;
			}
			if (tabsData.value[i].child_list) {
				for (let k = 0; k < tabsData.value[i].child_list.length; k++) {
					if (tabsData.value[i].child_list[k].category_id == categoryId) {
						tabActive.value = i;
						break;
					}
				}
			}
		}
	} else {
		categoryId = tabsData.value[0].category_id;
	}

}

// 一级菜单样式控制
const tabActive = ref<number>(0)

// 一级菜单点击事件
const firstLevelClick = (index: number, data: any) => {
	tabActive.value = index;
	categoryId = data.category_id;
	list.value = [];
	getMescroll().resetUpScroll();
}

// 搜索名字
const searchNameFn = () => {
	getMescroll().resetUpScroll();
}

//点击商品购物车按钮
const cartRef = ref()
const itemCart = (item: any, id: any) => {
	console.log(item)
	console.log(id)



	animationAddCart(item, id)


}


//进入购物车
const toCart = () => {
	redirect({ url: '/addon/pickUp/pages/goods/cart' })
}

//强制绑定手机号
const bindMobileRef: any = ref(null)
const isBindMobile = ref(uni.getStorageSync('isbindmobile'))

/**
 * 结算
 */
const settlement = () => {

	// #ifdef H5
	// 绑定手机号
	if (uni.getStorageSync('isbindmobile')) {
		bindMobileRef.value.open()
		return false
	}
	// #endif

	if (!totalNum.value) {
		uni.showToast({ title: '还没有选择商品', icon: 'none' })
		return
	}
	const cart_ids: any = []
	let items: any = []

	Object.values(cartList.value).forEach(item => {
		Object.keys(item).forEach(v => {
			if (v != 'totalNum' && v != 'totalMoney') cart_ids.push(item[v].id)
			item[v].cartId = item[v].id
			items.push(item[v])
		})

	})
	if (cart_ids.length == 0) {
		return;
	}

	uni.setStorage({
		key: 'serviceOrderCreateData',
		data: {
			cart_ids,
			items: items
		},
		success() {
			redirect({ url: '/addon/service/pages/order/payment' })
		}
	})
}


</script>

<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

.remove-border {
	&::after {
		border: none;
	}
}

.border-color {
	border-color: var(--primary-color) !important;
}

.text-color {
	color: var(--primary-color) !important;
}

.bg-color {
	background-color: var(--primary-color) !important;
}

.class-select {
	position: relative;
	font-weight: bold;

	&::before {
		content: "";
		position: absolute;
		bottom: 0;
		height: 6rpx;
		background-color: var(--primary-color);
		width: 90%;
		left: 50%;
		transform: translateX(-50%);
	}
}

.list-select {
	position: relative;
	margin-right: 28rpx;

	&::before {
		content: "";
		position: absolute;
		background-color: #999;
		width: 2rpx;
		height: 70%;
		top: 50%;
		right: -14rpx;
		transform: translatey(-50%);
	}
}

.transform-rotate {
	transform: rotate(180deg);
}

.text-color {
	color: var(--primary-color);
}

.bg-color {
	background-color: var(--primary-color);
}

// search input
.search-box {
	display: flex;
	align-items: center;
	padding: 0 30rpx;
}

.search-box .search-ipt {
	height: 58rpx;
	background-color: #F6F8F8;
	border-radius: 33rpx;
}

.search-box .search-ipt .input-placeholder {
	color: #A5A6A6;
}

.tabs-box {
	width: 168rpx;
	font-size: 32rpx;
}

.tabs-box .tab-item {
	min-height: 56rpx;
	padding: 20rpx 0;
	text-align: center;
	background-color: #fff;
	display: flex;
	align-items: center;
}

.tabs-box .tab-item-active {
	position: relative;
	color: var(--primary-color);
	background-color: var(--temp-bg);

	&::before {
		display: inline-block;
		position: absolute;
		left: 0rpx;
		top: 50%;
		transform: translateY(-50%);
		content: '';
		width: 6rpx;
		height: 48rpx;
		background-color: var(--primary-color);
	}

	&::after {
		display: inline-block;
		position: absolute;
		left: 0rpx;
		top: 50%;
		transform: translateY(-50%);
		content: '';
		width: 6rpx;
		height: 48rpx;
		background-color: var(--primary-color);
	}
}

.scroll-height {
	height: 100%;
}

/*  #ifdef  H5  */
.cart {
	.noData1 {
		height: calc(100vh - 146rpx - 100rpx - 50px - constant(safe-area-inset-bottom));
		height: calc(100vh - 146rpx - 100rpx - 50px - env(safe-area-inset-bottom));
	}

	.noData2 {
		height: calc(100vh - 40rpx - 100rpx - 50px - constant(safe-area-inset-bottom));
		height: calc(100vh - 40rpx - 100rpx - 50px - env(safe-area-inset-bottom));
	}
}

.detail {
	.noData1 {
		height: calc(100vh - 146rpx - 50px - constant(safe-area-inset-bottom));
		height: calc(100vh - 146rpx - 50px - env(safe-area-inset-bottom));
	}

	.noData2 {
		height: calc(100vh - 40rpx - 50px - constant(safe-area-inset-bottom));
		height: calc(100vh - 40rpx - 50px - env(safe-area-inset-bottom));
	}
}

/*  #endif  */
/*  #ifndef  H5  */
.cart {
	.noData1 {
		height: calc(100vh - 146rpx - 100rpx - 100rpx - constant(safe-area-inset-bottom));
		height: calc(100vh - 146rpx - 100rpx - 100rpx - env(safe-area-inset-bottom));
	}

	.noData2 {
		height: calc(100vh - 40rpx - 100rpx - 100rpx - constant(safe-area-inset-bottom));
		height: calc(100vh - 40rpx - 100rpx - 100rpx - env(safe-area-inset-bottom));
	}
}

.detail {
	.noData1 {
		height: calc(100vh - 146rpx - 100rpx - constant(safe-area-inset-bottom));
		height: calc(100vh - 146rpx - 100rpx - env(safe-area-inset-bottom));
	}

	.noData2 {
		height: calc(100vh - 40rpx - 100rpx - constant(safe-area-inset-bottom));
		height: calc(100vh - 40rpx - 100rpx - env(safe-area-inset-bottom));
	}
}

/*  #endif  */

// 空页面
.mescroll-empty.empty-page.part {
	width: 542rpx;
	height: 542rpx;
	margin-top: 0;
	margin-left: 0;
	padding-top: 50rpx;

	.img {
		width: 160rpx !important;
		height: 120rpx !important;
	}
}
</style>
